package com.sirui.spider.processor;

import cn.hutool.http.HttpUtil;
import com.sirui.spider.downloader.SeleniumDownloader;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.File;
import java.util.List;

public class MeiTouProcessor implements PageProcessor {
    private static final Site site = Site.me()
            .setDomain("www.imeitou.com")
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31")
            .setCharset("UTF-8")
            .setSleepTime(500);

    public static void main(String[] args) {
        Spider.create(new MeiTouProcessor())
                .addUrl("http://www.imeitou.com/katong/264283.html")
                .addPipeline(new JsonFilePipeline("d:\\logs\\webmagic\\"))
                .downloader(new SeleniumDownloader("D:\\tools\\webdriver\\chromedriver_win32\\chromedriver.exe"))
                .thread(5)
                .run();
    }

    @Override
    public void process(Page page) {
        // 加入其它页面
        //List<String> urlList = page.getHtml().links().regex("(http://www.imeitou.com/katong/(\\d+).html)").all();
        //page.addTargetRequests(urlList);
        // 保存信息
        List<String> srcList = page.getHtml().xpath("//div[@class='swipebox']/img/@src").all();
        page.putField("srcList", srcList);
        // 下载文件
        for (int i = 0; i < srcList.size(); i++) {
            String srcUrl = srcList.get(i);
            String fileName = srcUrl.substring(srcUrl.lastIndexOf("/") + 1);
            File file = new File("D:\\logs\\webmagic\\download2\\" + fileName);
            HttpUtil.downloadFile(srcUrl, file);
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}
